import time
import urllib.request
import numpy as np
import cv2
from PIL import Image
from selenium.webdriver import ActionChains
import ddddocr
from selenium.webdriver.common.by import By
from selenium import webdriver

#模拟浏览器登录---学习


username = input("请输入登录账号（手机号）：")
password = input("请输入登录密码：")
#
# print("请在弹出的网页中输入验证码！")
# time.sleep(2)
# 登录

driver = webdriver.Chrome()
driver.get('https://www.sqgj.gov.cn/')
driver.maximize_window()  #将浏览器最大化
time.sleep(2)
 
driver.find_element_by_xpath('//*[@id="new_mobilePhoneLogin"]').send_keys(username)
driver.find_element_by_xpath('//*[@id="new_passWordLogin"]').send_keys(password)

code = driver.find_element(By.CSS_SELECTOR, "#new_identifyCode")  # 验证码输入框位置
imgCode = driver.find_element(By.CSS_SELECTOR, "#getIdentifyCode")  # 验证码图片位置
 
imgCode.screenshot("code.png")  # 将验证码截图，保存为code.png
time.sleep(3)
# 以下为识别验证码的代码
ocr = ddddocr.DdddOcr(old=True)
with open("code.png", "rb") as f:
    image = f.read()
res= ocr.classification(image)  # 验证码返回给catch
code.send_keys(res)  # 将识别到的验证码输入到框内
time.sleep(2)
# 定位到登录按钮

driver.find_element_by_xpath('/html/body/div[3]/div[2]/div/div[1]/div[1]/div/div[1]/div[2]/ul[1]/li[4]/button').click()  # 登录
time.sleep(2)


button = driver.find_element_by_xpath('/html/body/div[8]/div/div/div[2]/div/div[2]/div/div')  # 找到滑动按钮
img1 = driver.find_element_by_xpath('/html/body/div[8]/div/div/div[2]/div/div[2]/div/div/div/img') .get_attribute('src')  # 找到待补全图并获取src属性
img2 = driver.find_element_by_xpath('/html/body/div[8]/div/div/div[2]/div/div[1]/div/img') .get_attribute('src')  # 找到缺口图并获取src属性
resp1 = urllib.request.urlopen(img1)  # 下载待补全图
image1 = np.asarray(bytearray(resp1.read()), dtype="uint8")
new_img1 = cv2.imdecode(image1, cv2.IMREAD_COLOR)  # cv2.imdecode()函数将数据解码成Opencv图像格式
resp2 = urllib.request.urlopen(img2)  # 下载待缺口图
image2 = np.asarray(bytearray(resp2.read()), dtype="uint8")
new_img2 = cv2.imdecode(image2, cv2.IMREAD_COLOR)  # cv2.imdecode()函数将数据解码成Opencv图像格式
cv2.imwrite('login1.jpg', new_img1)  # 保存在本地
cv2.imwrite('login2.jpg', new_img2)  # 保存在本地
im = Image.open('login1.jpg')  # 重新打开图像
im = im.resize((341, 195))  # 缩放
im.save('login1.jpg')
im = Image.open('login2.jpg')
im = im.resize((68, 68))  # 缩放
im.save('login2.jpg')
im1 = cv2.imread("login1.jpg")  # 再次打开
im2 = cv2.imread('login2.jpg')
bg_edge = cv2.Canny(im1, 100, 200)  # 识别图片边缘
tp_edge = cv2.Canny(im2, 100, 200)
bg_pic = cv2.cvtColor(bg_edge, cv2.COLOR_GRAY2RGB)  # 转换图片格式
tp_pic = cv2.cvtColor(tp_edge, cv2.COLOR_GRAY2RGB)
res = cv2.matchTemplate(bg_pic, tp_pic, cv2.TM_CCOEFF_NORMED)  # 缺口匹配
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)  # 寻找最优匹配
x = max_loc[0]  # 滑块在验证图片的x坐标（左边）
# 创建一个新的ActionChains，将webdriver实例对driver作为参数值传入，然后通过WenDriver实例执行用户动作
ActionChains(driver).click_and_hold(on_element=button).perform()
# 第一步：在滑块处按住鼠标左键
ActionChains(driver).move_by_offset(xoffset=x - 20, yoffset=0).perform()  # 鼠标移动到距离当前位置（x,y）
time.sleep(2)
# 第二步：相对鼠标当前位置进行移动
ActionChains(driver).release(on_element=button).perform()
# 第三步：释放鼠标
time.sleep(5)

xuexicishu = 0
# kecheng = driver.find_elements_by_xpath('/html/body/div[2]/div[2]/div/div[2]/div[3]/ul/li/ul[1]/li[1]')
# total_kecheng = len(kecheng)
while True:
    driver.find_element_by_xpath('/html/body/div[2]/div[2]/div/div[2]/div[3]/ul/li[1]/ul[1]/li[1]').click()

    time.sleep(5)
    xuexicishu = xuexicishu + 1
    windows = driver.window_handles
    driver.switch_to.window(windows[1])
    time.sleep(5)
    # 选择学习视频
    count = driver.find_elements_by_xpath(
        '/html/body/div[2]/div[2]/div[3]/div/div/div[2]/ul/li[@class !="hasStudy"]/span[2]')

    for i in range(0, len(count)):
        time.sleep(2)
        count = driver.find_elements_by_xpath(
            '/html/body/div[2]/div[2]/div[3]/div/div/div[2]/ul/li[@class !="hasStudy"]/span[2]')
        print(f"这是第{i+1}次学习")

        count[0].click()

        time.sleep(10)

        # 切换到播放窗口
        windows = driver.window_handles
        driver.switch_to.window(windows[2])

        # 确认课程学习时间
        keshi = driver.find_element_by_xpath('//*[@id="study"]/span[1]/strong').text
        print(f"本科总课时{keshi}")
        yixueshijian = driver.find_element_by_xpath('/html/body/div[2]/div[2]/div[2]/div[1]/span[2]/strong').text
        if int(keshi) - int(yixueshijian) > 0:
            study_time = int(keshi) - int(yixueshijian)
        else:
            study_time = 1
        print(f"本次需要学习{study_time}分钟")
        iframe = driver.find_element_by_xpath('//*[@id="playResourceFrame"]')

        driver.switch_to_frame(iframe)
        time.sleep(3)
        driver.find_element_by_xpath('/html/body/div[2]/div/div[3]/div[2]').click()
        time.sleep(study_time * 60 + 63)

        # 点击退出

        time.sleep(3)
        driver.find_element_by_xpath('//*[@id="exit"]').click()
        time.sleep(3)
        driver.switch_to_alert().accept()
        time.sleep(3)
        driver.switch_to_alert().accept()
        time.sleep(5)
        windows = driver.window_handles
        driver.switch_to.window(windows[1])
        driver.refresh()
        time.sleep(6)
    driver.close()
    windows = driver.window_handles
    driver.switch_to.window(windows[0])
    driver.refresh()
    time.sleep(5)

    print("干部培训网，完成第" + str(xuexicishu) + "次学习")



